package org.meow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.meow.dto.ArticleDTO;
import org.meow.dto.ArticlePageDTO;
import org.meow.entity.Article;
import org.meow.mapper.ArticleMapper;
import org.meow.service.ArticleService;
import org.meow.utils.MeowStr;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * &#064;Date: 24/04/26-22:31
 * &#064;Description:
 */
@Service
public class ArticleServiceImpl implements ArticleService {

  @Autowired
  private ArticleMapper articleMapper;

  @Override
  public void save(ArticleDTO articlesDTO) {
    Article article = new Article();
    BeanUtils.copyProperties(articlesDTO, article);
    article.setPublishDateTime(LocalDateTime.now());
    article.setModifyDateTime(LocalDateTime.now());
    articleMapper.insert(article);
  }

  @Override
  public boolean delete(Integer id) {
    return articleMapper.deleteById(id) != 0;
  }

  @Override
  public boolean update(Article article) {
    LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
    updateWrapper
        .eq(Article::getId, article.getId())
        .set(MeowStr.isStrNotBlank(article.getTitle()), Article::getTitle, article.getTitle())
        .set(MeowStr.isStrNotBlank(article.getContent()), Article::getContent, article.getContent())
        .set(MeowStr.isStrNotBlank(article.getBrief()), Article::getBrief, article.getBrief())
        .set(MeowStr.isStrNotBlank(article.getImage()), Article::getImage, article.getImage())
        .set(article.getArticleGroupId() != null, Article::getArticleGroupId, article.getArticleGroupId())
        .set(Article::getModifyDateTime, LocalDateTime.now());
    return articleMapper.update(null, updateWrapper) != 0;
  }

  @Override
  public List<Article> getArticlesByCateId(Integer id) {
    return articleMapper.getArticlesByCateId(id);
  }

  @Override
  public IPage<Article> pageQuery(ArticlePageDTO artPageDTO) {
    IPage<Article>              page         = new Page<>(artPageDTO.getCurr(), artPageDTO.getSize());
    LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Article::getArticleGroupId, artPageDTO.getArticleGroupId());
    return articleMapper.selectPage(page, queryWrapper);
  }
}
